<template>
	<view class="custom_form">
		<view class="custom_form_body">
			<view class="custom_form_body_item">
				<text><text>*</text>孩子姓名</text>
				<u-input placeholder="请输入孩子姓名" inputAlign="right" v-model="fromValue.studentName" border="none"
					:clearable="true" placeholderClass="placeholderClass"></u-input>
			</view>
			<view class="custom_form_body_item">
				<text><text>*</text>身份证号</text>
				<u-input placeholder="请输入身份证号" inputAlign="right" v-model="fromValue.idcard" border="none"
					:clearable="true" type="idcard" @change="handleChangeIdcard"
					placeholder-style="font-size:28rpx;color:#666666"></u-input>
			</view>
			<view class="custom_form_body_item" @click="handlePickerShow('sex')">
				<text><text>*</text>性别</text>
				<view class="custom_form_body_item_right">
					<text v-if="fromValue?.sex">{{sexText}}</text>
					<text v-else class="placeholder">请输入身份证号</text>
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view>
			<view class="custom_form_body_item">
				<text><text>*</text>年龄</text>
				<u-input placeholder="请输入年龄" inputAlign="right" v-model="fromValue.age" border="none" readonly
					:clearable="true" type="number" placeholderClass="placeholderClass">
					<template #suffix>岁</template></u-input>
			</view>
			<view class="custom_form_body_item" @click="handlePickerShow('school')">
				<text><text>*</text>学校</text>
				<view class="custom_form_body_item_right">
					<text v-if="fromValue?.schoolName">{{fromValue?.schoolName}}</text>
					<text v-else class="placeholder">请选择学校</text>
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view>
			<view class="custom_form_body_item" @click="handlePickerShow('grade')">
				<text><text>*</text>年级</text>
				<view class="custom_form_body_item_right">
					<text v-if="fromValue?.gradeName">{{fromValue?.gradeName}}</text>
					<text v-else class="placeholder">请选择年级</text>
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view>
			<view class="custom_form_body_item" @click="handlePickerShow('class')">
				<text><text>*</text>班级</text>
				<view class="custom_form_body_item_right">
					<text v-if="fromValue?.className">{{fromValue?.className}}</text>
					<text v-else class="placeholder">请选择班级</text>
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view>
			<view class="custom_form_body_item">
				<text style="width:230rpx"><text>*</text>家长联系电话</text>
				<u-input placeholder="请输入家长联系电话" inputAlign="right" v-model="fromValue.phone" border="none"
					:clearable="true" placeholderClass="placeholderClass"></u-input>
			</view>
			<view class="custom_form_body_item" @click="handleUplad">
				<text>头像</text>
				<view class="custom_form_body_item_right">
					<image :src="fromValue?.avatar" v-if="fromValue?.avatar"></image>
					<image src="http://qianxueapplet.suoeryun.com/child.png" v-else></image>
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view>
		</view>
		<view class="custom_form_btn" @click="handleSave">保存</view>
		<!--  性别选择-->
		<u-picker :show="isSexShow" :columns="columns" keyName="text" @confirm="handleSexConfirm"
			@cancel="handlePickerCancel('sex')"></u-picker>
		<!--  学校选择-->
		<u-picker :show="isSchoolShow" :columns="columnsSchool" keyName="name" @confirm="handleSchoolConfirm"
			@cancel="handlePickerCancel('school')"></u-picker>
		<!--  年级选择-->
		<u-picker :show="isGradeShow" :columns="columnsGrade" keyName="name" @confirm="handleGradeConfirm"
			@cancel="handlePickerCancel('grade')"></u-picker>
		<!--  班级选择-->
		<u-picker :show="isClassShow" :columns="columnsClass" keyName="name" @confirm="handleClassConfirm"
			@cancel="handlePickerCancel('class')"></u-picker>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted, reactive, computed, toRaw, unref, getCurrentInstance } from "vue";
	import config from '@/common/config';
	import { getDictItemsByCode } from '@/config/sys.api';
	import { querySchoolTreeList, queryStudentInfoByIdCard, qxStudentManageEdit, addBindingStudentInfo, qxStudentManageQueryById } from '@/config/mine.api';
	import { onLoad } from "@dcloudio/uni-app";
	import { discriCard, getSexByIdCard } from '@/util/index';
	// import ObsClient from 'esdk-obs-nodejs';
	// import ObsClient from '../../util/esdk-obs-browserjs-without-polyfill-3.21.8.min.js';
	// import ObsClient from '../../util/esdk-obs-browserjs.3.23.5.min.js';

	// const ObsClient = require('../../util/esdk-obs-browserjs.3.23.5.min.js');
	// const ObsClient = require('../../util/esdk-obs-browserjs-without-polyfill-3.21.8.min.min.js');

	// 表单数据
	const fromValue = reactive({
		"age": '',
		"avatar": "",
		"classId": "",
		"className": "",
		"createBy": "",
		"createTime": "",
		"gradeId": "",
		"gradeName": "",
		"id": "",
		"idcard": "",
		"phone": "",
		"schoolId": "",
		"schoolName": "",
		"sex": "",
		"studentName": "",
		"updateBy": "",
		"updateTime": ""
	});
	const isSexShow = ref(false);
	const isSchoolShow = ref(false);
	const isGradeShow = ref(false);
	const isClassShow = ref(false);
	// 性别
	const columns = reactive([]);
	// 学校
	const columnsSchool = reactive([]);
	// 年纪
	const columnsGrade = reactive([]);
	// 班级
	const columnsClass = reactive([]);
	const { proxy } = getCurrentInstance();


	onMounted(async () => {
		// 性别
		const res = await getDictItemsByCode({ dictCode: 'sex' });
		columns.push(res);
		// 学校树
		const data = await querySchoolTreeList({});
		columnsSchool.push(data);
	});

	onLoad(async (params) => {
		if (params?.id) {
			const res = await qxStudentManageQueryById({ id: params?.id });
			fromValue.id = res?.id;
			formAssignment(res);
		} else {
			fromValue.phone = toRaw(proxy['vuex_user'])['phone']
		}
	})

	/**
	 * 性别中文显示
	 */
	const sexText = computed(() => {
		if (fromValue?.sex && columns?.length > 0) {
			let arrFilter = toRaw(columns)[0]?.filter(item => item?.value == fromValue?.sex);
			if (arrFilter?.length > 0) {
				return arrFilter[0]['text'];
			}
			return '';
		}
		return '';
	})

	/**
	 * 头像上传
	 */
	function handleUplad(e) {
		uni.chooseImage({
			count: 1,
			success: (chooseImageRes) => {
				uni.showLoading({
					title: '上传头像中...'
				})
				const tempFilePaths = chooseImageRes.tempFilePaths;
				// let obsClient = new ObsClient({
				// 	access_key_id: 'FA2NYNXOJWPGIGFAO9XC',
				// 	secret_access_key: 'BE9mVHP7VSMzBfu2QgKyozbgwv0YEHUIaauvkmzW',
				// 	server: 'https://qianxunyanxue-applet.obs.cn-north-4.myhuaweicloud.com' // 你的endPoint
				// });
				// console.log(obsClient, 'obsClient');
				// obsClient.putObject({
				// 	Bucket: 'qianxunyanxue-applet',
				// 	Key: `mini/aa.png`, // 路径 + 文件名
				// 	SourceFile: tempFilePaths[0]
				// }, (err, result) => {
				// 	console.log(err, result);
				// })

				// uni.uploadFile({
				// 	url: 'https://qianxunyanxue-applet.obs.cn-north-4.myhuaweicloud.com',
				// 	// url: config.baseUrl + '/sys/common/obsUpload', //仅为示例，非真实的接口地址
				// 	filePath: tempFilePaths[0],
				// 	name: 'file',
				// 	header: {
				// 		'Authorization:': 'OBS FA2NYNXOJWPGIGFAO9XC:p206oqZCDAKDsMkq4IsrFr9V+dU='
				// 	},
				// 	formData: {
				// 		'key': 'mini/12.jpg',//地址和文件名
				// 		'AccessKeyId': 'FA2NYNXOJWPGIGFAO9XC',  //获取ak
				// 		// 'Policy': '',  //获取后端生成的policy
				// 		'x-obs-acl': 'public-read',  //设置为公共读
				// 		'content-type': 'jpg',  //文件类型
				// 		// 'Signature': '' //获取后端生成的signature 
				// 	},
				// 	success: (uploadFileRes) => {
				// 		uni.hideLoading()
				// 		fromValue.avatar = JSON.parse(uploadFileRes.data)?.message;
				// 	},
				// 	fail() {
				// 		uni.hideLoading()
				// 		uni.showToast({
				// 			icon: 'none',
				// 			title: '接口异常！'
				// 		})
				// 	}
				// });


				uni.uploadFile({
					// url: 'http://qianxueapplet.suoeryun.com/mini',
					url: config.baseUrl + '/sys/common/obsUpload', //仅为示例，非真实的接口地址
					// url: config.baseUrl + '/sys/common/upload', //仅为示例，非真实的接口地址
					filePath: tempFilePaths[0],
					name: 'file',
					header: {
						'X-Access-Token': unref(proxy['vuex_token'])
					},
					success: (uploadFileRes) => {
						uni.hideLoading()
						fromValue.avatar = JSON.parse(uploadFileRes.data)?.message;
					},
					fail() {
						uni.hideLoading()
						uni.showToast({
							icon: 'none',
							title: '接口异常！'
						})
					}
				});
			},
			fail() {
				uni.hideLoading()
			}
		});
	}

	/**
	 * 性别选择
	 */
	function handlePickerShow(type) {
		if (type === 'sex') {
			return
			// isSexShow.value = true;
		} else if (type === 'school') {
			isSchoolShow.value = true;
		} else if (type === 'grade') {
			console.log(columnsSchool, 'columnsSchool');
			if (!fromValue.schoolName) {
				return uni.showToast({
					icon: 'none',
					title: '请选择学校！'
				})
			}
			isGradeShow.value = true;
		} else if (type === 'class') {
			if (!fromValue?.gradeName) {
				return uni.showToast({
					icon: 'none',
					title: '请选择年纪！'
				})
			}
			isClassShow.value = true;
		}
	}

	/**
	 * 性别选择器 确认
	 */
	function handleSexConfirm(arr) {
		if (arr?.value?.length > 0) {
			fromValue.sex = arr.value[0].value;
		}
		isSexShow.value = false;
	}

	/**
	 * 学校选择器 确认
	 */
	function handleSchoolConfirm(arr) {
		if (arr?.value?.length > 0) {
			const item = toRaw(arr.value[0]);
			fromValue.schoolId = item?.id;
			fromValue.schoolName = item?.name;
			columnsGrade.length = 0;
			columnsGrade.push(item?.childs);
			fromValue.gradeId = '';
			fromValue.gradeName = '';
			fromValue.classId = '';
			fromValue.className = '';
		}
		isSchoolShow.value = false;
	}

	/**
	 * 年级选择器 确认
	 */
	function handleGradeConfirm(arr) {
		if (arr?.value?.length > 0) {
			const item = toRaw(arr.value[0]);
			fromValue.gradeId = item?.id;
			fromValue.gradeName = item?.name;
			fromValue.classId = '';
			fromValue.className = '';
			columnsClass.length = 0;
			columnsClass.push(item?.childs);
		}
		isGradeShow.value = false;
	}

	/**
	 * 班级选择器 确认
	 */
	function handleClassConfirm(arr) {
		if (arr?.value?.length > 0) {
			const item = toRaw(arr.value[0]);
			fromValue.classId = item?.id;
			fromValue.className = item?.name;
		}
		isClassShow.value = false;
	}

	/**
	 * 性别选择器 取消
	 */
	function handlePickerCancel(type) {
		if (type === 'sex') {
			isSexShow.value = false;
		} else if (type === 'school') {
			isSchoolShow.value = false;
		} else if (type === 'grade') {
			isGradeShow.value = false;
		} else if (type === 'class') {
			isClassShow.value = false;
		}
	}

	/**
	 * 身份证号校验
	 */
	async function handleChangeIdcard(e) {
		if (e?.length === 18) {
			if (uni.$u.test.idCard(e)) {
				const res = await queryStudentInfoByIdCard({ idCard: e });
				console.log(res);
				if (!uni.$u.test.isEmpty(res)) {
					formAssignment(res);
				} else {
					fromValue.age = discriCard(e).toString();
					fromValue.sex = getSexByIdCard(e);
					// fromValue.studentName = '';
					// fromValue.schoolId = '';
					// fromValue.schoolName = '';
					// fromValue.gradeId = '';
					// fromValue.gradeName = '';
					// fromValue.classId = '';
					// fromValue.className = '';
					// fromValue.phone = '';
					// fromValue.avatar = '';
				}
			} else {
				uni.showToast({
					icon: 'none',
					title: '请输入正确格式身份证号！'
				})
			}
		}
	}

	/**
	 * 表单赋值
	 */
	function formAssignment(res) {
		fromValue.studentName = res?.studentName;
		fromValue.idcard = res?.idcard;
		fromValue.sex = res?.sex;
		fromValue.age = res?.age;
		fromValue.schoolId = res?.schoolId;
		fromValue.schoolName = res?.schoolName;
		fromValue.gradeId = res?.gradeId;
		fromValue.gradeName = res?.gradeName;
		fromValue.classId = res?.classId;
		fromValue.className = res?.className;
		fromValue.phone = res?.phone;
		fromValue.avatar = res?.avatar;
	}

	/**
	 * 保存
	 */
	async function handleSave() {
		const params = fromValue;
		if (params?.studentName === '' || !params?.studentName) {
			return uni.showToast({
				icon: 'none',
				title: '请输入孩子姓名！'
			})
		}
		if (params?.idcard === '' || !params?.idcard) {
			return uni.showToast({
				icon: 'none',
				title: '请输入身份证号！'
			})
		}
		if (!uni.$u.test.idCard(params?.idcard)) {
			return uni.showToast({
				icon: 'none',
				title: '请输入正确格式身份证号！'
			})
		}
		if (params?.sex === '' || !params?.sex) {
			return uni.showToast({
				icon: 'none',
				title: '请选择性别！'
			})
		}
		if (params?.age === '' || !params?.age) {
			return uni.showToast({
				icon: 'none',
				title: '请输入年龄！'
			})
		}
		if (params?.schoolName === '' || !params?.schoolName) {
			return uni.showToast({
				icon: 'none',
				title: '请选择学校！'
			})
		}
		if (params?.gradeName === '' || !params?.gradeName) {
			return uni.showToast({
				icon: 'none',
				title: '请选择年级！'
			})
		}
		if (params?.className === '' || !params?.className) {
			return uni.showToast({
				icon: 'none',
				title: '请选择班级！'
			})
		}
		if (params?.phone === '' || !params?.phone) {
			return uni.showToast({
				icon: 'none',
				title: '请输入家长联系电话！'
			})
		}
		if (!uni.$u.test.mobile(params?.phone)) {
			return uni.showToast({
				icon: 'none',
				title: '请输入正确格式手机号码！'
			})
		}
		uni.showLoading({
			title: '保存中...'
		})
		if (params?.id) {
			await qxStudentManageEdit(params);
		} else {
			await addBindingStudentInfo(params);
		}
		uni.showToast({
			icon: 'none',
			title: '保存成功'
		});
		uni.$u.route({ type: 'back' });
	}
</script>

<style lang="scss" scoped>
</style>